<?php
namespace App\Handlers;

use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
use App\Models\CrawlerUrl;
use Image;
use App\Services\OSS;
use Illuminate\Support\Facades\Storage;

class DownLoadPictuerHandler
{
    public function download($url)
    {
        $client = new Client();
        if ($response = $client->request('GET', $url, [
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
            ],
            'timeout' => 3.14,
            'verify' => true
         ])) {
            return $response->getBody();
        } else {
            return false;
        }
    }

    protected function get_pictuer_origin_url($url)
    {
        $urlInfo = parse_url($url);
        if (strstr($urlInfo['host'], 'woyaogexing.com')) {
            // 我要个性网替换规则
            return preg_replace('/\!([0-9]+)x([0-9]+)(_big)?/i','', $url);
        }
        return $url;
    }

    public function info($url)
    {
        if(!$content = $this->download($this->get_pictuer_origin_url($url))) return false;
        $img = Image::make($content);
        //return $img->encode();
        return $result = [
            'width' => $img->width(),
            'height' => $img->height(),
            'content' => (string) $img->encode(),
            'mime' => $img->mime(),
            'size' => $img->filesize()/1024
        ];
    }
    public function upload($url)
    {
        if(!$result = $this->info($url)) return false;

        $path = date("Ym/d", time());

        $filename = time() . '_' . str_random(32);

        if (\App::environment('local')) {
            // 如果是本地环境 就保存在本地
            $isUpload = Storage::disk('local')->put('public/uploads/' . $path . '/' . $filename, $result['content']);
            $domain = '';
        } else {
            // 非本地环境，上传到 OSS
            $domain = config('services.oss.domain', 'pic.touxiangge.com');
            $isUpload = OSS::privateUploadContent(config('services.oss.bucketname'),  $path . '/' . $filename, $result['content'], [
                'ContentType' => $result['mime'],
            ]);
        }

        if($isUpload) {
            // 保存或上传成功，返回图片信息
            if ($result['width'] >= 400 && $result['height'] >= 400) $hd = 1;
            else $hd = 0;
            return [
                'width' => $result['width'],
                'height' => $result['height'],
                'mime' => $result['mime'],
                'path' => $path,
                'filename' => $filename,
                'size' => $result['size'],
                'hd' => $hd,
                'domain' => $domain,
                'md5' => md5($result['content'])
            ];
        }
        return false;
    }
}
